package cn.jjzd.info.service;

import cn.jjzd.info.config.SettingProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

@Service
@EnableConfigurationProperties(SettingProperties.class)
public class InfoHtmlService {
    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private InfoService infoService;

    @Autowired
    private SettingProperties settingProperties;

    public void createHtml(Long id,Integer type){

        //初始化运行上下文
        Context context = new Context();
        //设置数据模型
        String dirName = "";
        if(type == 1){
            dirName = "info";
            context.setVariables(this.infoService.loadDetailData(id));
        }else if(type == 2){
            dirName = "category";
            context.setVariables(this.infoService.loadMoreData(id));
        }

        File file = new File(settingProperties.getNginxPath() + dirName + File.separator + id + ".html");
        PrintWriter printWriter = null;
            try {
            printWriter = new PrintWriter(file);
            if(type == 1){
                this.templateEngine.process("detailsPage",context,printWriter);
            }else if(type == 2){
                this.templateEngine.process("morePage",context,printWriter);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if(printWriter != null){
                printWriter.close();
            }
        }

    }

    public void deleteHtml(Long id,Integer type) {
        String dirName = "";
        if(type == 1){
            dirName = "info";
        }else if(type == 2){
            dirName = "category";
        }
        File file = new File(settingProperties.getNginxPath() + dirName + File.separator + id + ".html");
        file.deleteOnExit();
    }
}
